import {Injectable} from "@nestjs/common";
import {SurveyIssueEntity} from "./entities/survey-issue.entity";
import {DataSource, Repository} from "typeorm";
import {InjectRepository} from "@nestjs/typeorm";
import {tempSaveDto} from "./dto/survey-issue.dto";
import {RedisService} from "../../common/redis/redis.service";
import {CacheEnum} from "../../../common/enum";
import {ResultData} from "../../../common/utils/result";
import {CreateIssueDto} from "../issue/dto/issue-dto";
import { IssueEntity } from "../issue/entities/issue.entity";


@Injectable()
export class SurveyIssueService {
    constructor(
        private dataSource: DataSource,
        @InjectRepository(SurveyIssueEntity)
        private  readonly  surveyIssueEntityRep: Repository<SurveyIssueEntity>,
        private readonly redisService: RedisService,
        @InjectRepository(IssueEntity)
        private readonly issueEntityRep: Repository<IssueEntity>
    ) {}

    /**
     * 查找某个问卷的题目内容
     * @param surId
     */
    async findOne(surId: number){
        let data = await this.redisService.get(`${CacheEnum.FEED_SUR_KEY}${surId}`)
        if(data){
            return ResultData.ok(data)
        }
        const entity = this.surveyIssueEntityRep.createQueryBuilder("entity")
        entity.leftJoinAndSelect("entity.issue",'issue')
        entity.where({ surId })
        const list = await entity.getMany()
        const result = list.map(item=>({
            ...item.issue,
            score: item.score,
        }))
        // 存入redis
        await this.redisService.set(`${CacheEnum.FEED_SUR_KEY}${surId}`,result,  1000 * 60 * 60 * 24)
        return  ResultData.ok(result)
    }

    /**
     * 批量保存题目及其与问卷的关联关系
     * @param surId 问卷ID
     * @param data 题目DTO数组
     */
    batchSave =async (surId: string, data: CreateIssueDto[]) => {
        const queryRunner = this.dataSource.createQueryRunner();
        await queryRunner.connect();
        await queryRunner.startTransaction();
        try {
            // Step 1: 分离出需要更新和新增的数据
            const updateData = data.filter(dto => dto.issueId);
            const createData = data.filter(dto => !dto.issueId);

            // Step 2: 更新已有题目
            let updatedIssues: IssueEntity[] = [];
            if (updateData.length > 0) {
                updatedIssues = await queryRunner.manager.save(
                    IssueEntity,
                    updateData.map(dto => ({
                        ...dto,
                        issueId: dto.issueId,
                    }))
                );
            }
            // Step 3: 新增题目
            let createdIssues: IssueEntity[] = [];
            if (createData.length > 0) {
                createdIssues = await queryRunner.manager.save(IssueEntity, createData);
            }
            // Step 4: 提取所有题号ID与对应score
            const allSavedIssues = [...updatedIssues, ...createdIssues];
            const issueScoreMap = allSavedIssues.map(issue => {
                const dto = data.find(d => d.issueId === issue.issueId)!;
                return {
                    issueId: issue.issueId,
                    score: dto.score ?? 0,
                };
            });
            // Step 5: 删除旧的关联记录
            await queryRunner.manager.delete(SurveyIssueEntity, { surId: +surId });

            // Step 6: 创建新的关联记录（含 score）
            const relations = issueScoreMap.map(({ issueId, score }) =>
                this.surveyIssueEntityRep.create({
                    surId: +surId,
                    issueId,
                    score,
                })
            );

            // Step 7: 批量保存新的关联记录
            await queryRunner.manager.save(SurveyIssueEntity, relations);

            // Step 8: 提交事务
            await queryRunner.commitTransaction();

            // Step 9: 清除 Redis 缓存
            await this.redisService.del(`${CacheEnum.FEED_SUR_KEY}${surId}`);
            // 同步最新数据给前端
            return ResultData.ok();
        } catch (error) {
            console.log(error)
            await queryRunner.rollbackTransaction();
            return ResultData.fail(500,`批量保存失败：${error.message}`);
        } finally {
            await queryRunner.release();
        }
    }
}
